package ait642.towson.edu;

import java.io.*;

/**\
 * @author Tariku Tessema Task -4 Modifying Code
 */
public class Stutter {

	/**
	 * The main method.
	 * 
	 * @param args
	 *            the file path
	 */
	public static void main(String[] args) {

		String fileName;
		String stutterCheck;
		boolean hasStutter = false;

		if (args.length > 0) {
			fileName = args[0];
			Integer lineNumber;
			lineNumber = 1;

			try {
				BufferedReader input = new BufferedReader(new FileReader(
						fileName));
				String line = null; // Text contained in a line
				try {
					while ((line = input.readLine()) != null) {
						stutterCheck = getStutteredWord(line, lineNumber);
						if (stutterCheck != "") {
							hasStutter = true;
							printStutteredWord(stutterCheck, lineNumber);
						}
						lineNumber++;
					}
					if (hasStutter == false) {
						System.out.print("No stutter found");
					}
				} catch (IOException e) {
					// Handle line exceptions
					e.printStackTrace();
				}

			} catch (FileNotFoundException e) {
				// Handle file exceptions
				e.printStackTrace();
			}

		} else {
			System.out.print("No file selected");
		}

	}

	/**
	 * Gets the stuttered word.
	 * 
	 * @param newLine
	 *            the new line
	 * @param lineNumber
	 *            the line number
	 * @return the stuttered word
	 */
	public static String getStutteredWord(String newLine, Integer lineNumber) {
		String word = "";
		int i = 0;

		for (i = 0; i < newLine.split(" ").length; i++) {
			// Check the word before current selected word
			if (i > 0) {
				if (newLine.split(" ")[i - 1].toString().equalsIgnoreCase(
						newLine.split(" ")[i].toString())) {
					word = newLine.split(" ")[i].toString();
				}
				// Check the word after current selected word
				if (i < newLine.split(" ").length - 1) {
					if (newLine.split(" ")[i + 1].toString().equalsIgnoreCase(
							newLine.split(" ")[i].toString())) {
						word = newLine.split(" ")[i].toString();
					}
				}
			}
		}
		return word;
	}

	/**
	 * Prints the stuttered word.
	 * 
	 * @param word
	 *            the word
	 * @param lineNumber
	 *            the line number
	 */
	public static void printStutteredWord(String word, Integer lineNumber) {
		String strRtn;
		strRtn = "";

		strRtn += "Line Number :" + String.valueOf(lineNumber)
				+ " ------------- " + word
				+ System.getProperty("line.separator");
		System.out.print(strRtn);
	}
}
